package org.tulkas.test.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import junit.framework.AssertionFailedError;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.tulkas.util.FileUtil;

public abstract class THandler extends AbstractHandler {
	private Error testError;

	public void handle(String target, Request baseRequest,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		baseRequest.setHandled(true);
		testError = null;

		try {
			this.handle(request, response);
		} catch (AssertionFailedError e) {
			testError = e;
		} catch (AssertionError e) {
			testError = e;
		}
	}

	public void handleAssertions() {
		if (testError != null)
			throw testError;
	}

	protected void outputResource(String path, HttpServletResponse response)
			throws IOException {
		InputStream in = this.getClass().getClassLoader().getResourceAsStream(
				path);

		OutputStream out = response.getOutputStream();
		FileUtil.readAndWrite(in, out);
		in.close();
	}

	protected abstract void handle(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException;
}
